package com.zlzxm.sorting.util

import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultCaller
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
 
/**
 * 使用registerForActivityResult请求权限封装
 * @param caller 调用者，一般为Activity
 * */
public class PermissionLauncher(caller: ActivityResultCaller) {
 
    // 请求权限，支持单、多权限申请
    private var launcher: ActivityResultLauncher<Array<String>>
 
    // 权限申请结果回调
    private lateinit var callback: ActivityResultCallback<Boolean>
 
    // 是否多权限
    private var multiPermission = false
 
    init {
        launcher = caller.registerForActivityResult(
            ActivityResultContracts.RequestMultiplePermissions()
        ) {
            // 多权限返回是否全部通过结果
            callback.onActivityResult(
                if (multiPermission) it.values.contains(false).not()
                else it.values.first()
            )
        }
    }
 
    /**
     * 启动请求权限
     * @param permissions 权限列表
     * @param callback 权限申请结果回调
     * */
    fun launch(
        permissions: Array<String>,
        callback: ActivityResultCallback<Boolean>
    ) {
        this.callback = callback
        // 是否多权限，回调区分处理
        multiPermission = permissions.size > 1
        launcher.launch(permissions)
    }
}